<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>碰撞</title>
	<style>
		.box{
			width: 800px;
			height: 300px;
			border:1px solid black;
			position: relative;
		}
		.box div{
			width: 100px;
			height: 100px;
			background-color: red;
			opacity: 0.7;
			border-radius: 50%;

		}
		.right{
			/*定位在右上角*/
			position: absolute;
			top: 0;
			right: 0;
		}


	</style>
</head>

<body>
	<div class="box">
		<div class="left"></div>
		<div class="right"></div>
	</div>
</body>
<script>
	var leftDiv = document.getElementsByClassName('left')[0];
	var rightDiv = document.getElementsByClassName('right')[0];

	var num = 0;
	var speed = 1;
	var timer = setInterval(function  () {
		num+=speed;
		if(num == 300){
			speed *= -1;
			leftDiv.style.backgroundColor = 'green';
			rightDiv.style.backgroundColor = 'yellow';
		}
		if(num ==0){
			speed *= -1;
			leftDiv.style.backgroundColor = 'red';
			rightDiv.style.backgroundColor = 'red';
		}
		leftDiv.style.marginLeft = num +'px';
		rightDiv.style.marginRight = num + 'px';
	},10);











</script>
</html>